package com.superbytecode.cloud.redis;

import com.superbytecode.cloud.redis.aspect.LockAspect;
import com.superbytecode.cloud.redis.lock.LockProperties;
import com.superbytecode.cloud.redis.lock.Locker;
import com.superbytecode.cloud.redis.lock.RedissonLocker;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: sanskrit
 * @Package: com.superbytecode.cloud.redis
 * @ClassName: RedissonAutoConfiguration
 * @Description: [Redisson配置]
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/8/19 11:09
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.cn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({RedisProperties.class, LockProperties.class})
@Import({LockAspect.class})
public class RedissonAutoConfiguration {

    @Bean
    public RedissonClient redissonClient(@Value("${spring.redis.host}") String host, //
                                         @Value("${spring.redis.port}") String port,//
                                         @Value("${spring.redis.password}") String password,//
                                         @Value("${spring.redis.database:0}") int database) {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        // redis服务地址格式：“redis://host:port”
        String SERVER_ADDR = String.format("redis://%s:%s", host, port);
        singleServerConfig.setAddress(SERVER_ADDR).setPassword(password);
        singleServerConfig.setConnectionMinimumIdleSize(1);
        singleServerConfig.setDatabase(database);
        return Redisson.create(config);
    }

    /**
     * 注入分布式锁，业务框架有需要也可以自己实现
     */
    @Bean
    @ConditionalOnMissingBean(Locker.class)
    public Locker locker(LockProperties lockProperties, RedissonClient redissonClient) {
        return new RedissonLocker(lockProperties.getType(), redissonClient);
    }
}